<template>
  <div class="page-container">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="back-btn" @click="goBack">
        <Left />
      </div>
      <h1 class="title">确认订单</h1>
      <div class="placeholder"></div>
    </div>

    <!-- 收货地址 -->
    <div class="address-section">
      <div class="section-title">收货地址</div>
      <div class="address-item" @click="selectAddress">
        <div class="address-info" v-if="selectedAddress">
          <div class="contact-info">
            <span class="name">{{ selectedAddress.name }}</span>
            <span class="phone">{{ selectedAddress.phone }}</span>
          </div>
          <div class="address-detail">
            {{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.district }} {{ selectedAddress.address }}
          </div>
        </div>
        <div class="no-address" v-else>
          <span>请选择收货地址</span>
        </div>
        <Right class="arrow" />
      </div>
    </div>

    <!-- 商品信息 -->
    <div class="products-section">
      <div class="section-title">商品信息</div>
      <div class="product-list">
        <div 
          class="product-item" 
          v-for="product in cartStore.selectedItems" 
          :key="product.id"
        >
          <div class="product-image">
            <img :src="product.image" :alt="product.name" />
          </div>
          <div class="product-info">
            <h4 class="product-name">{{ product.name }}</h4>
            <div class="product-spec" v-if="product.selectedSpec">{{ product.selectedSpec }}</div>
            <div class="product-price">
              <span class="price">¥{{ product.price }}</span>
              <span class="quantity">x{{ product.quantity }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 配送方式 -->
    <div class="delivery-section">
      <div class="section-title">配送方式</div>
      <div class="delivery-options">
        <div 
          class="delivery-option" 
          :class="{ active: deliveryMethod === 'express' }"
          @click="deliveryMethod = 'express'"
        >
          <div class="option-info">
            <span class="option-name">快递配送</span>
            <span class="option-desc">2-3个工作日送达</span>
          </div>
          <div class="option-price">¥{{ deliveryFee }}</div>
        </div>
        <div 
          class="delivery-option" 
          :class="{ active: deliveryMethod === 'self' }"
          @click="deliveryMethod = 'self'"
        >
          <div class="option-info">
            <span class="option-name">到店自提</span>
            <span class="option-desc">免费，需到指定门店</span>
          </div>
          <div class="option-price">免费</div>
        </div>
      </div>
    </div>

    <!-- 优惠券 -->
    <div class="coupon-section">
      <div class="section-title">优惠券</div>
      <div class="coupon-item" @click="selectCoupon">
        <div class="coupon-info">
          <span class="coupon-name">{{ selectedCoupon ? selectedCoupon.name : '选择优惠券' }}</span>
          <span class="coupon-desc" v-if="selectedCoupon">{{ selectedCoupon.description }}</span>
        </div>
        <Right class="arrow" />
      </div>
    </div>

    <!-- 支付方式 -->
    <div class="payment-section">
      <div class="section-title">支付方式</div>
      <div class="payment-options">
        <div 
          class="payment-option" 
          :class="{ active: paymentMethod === 'wechat' }"
          @click="paymentMethod = 'wechat'"
        >
          <div class="option-info">
            <img src="https://picsum.photos/24/24?random=1" alt="微信支付" class="payment-icon" />
            <span class="option-name">微信支付</span>
          </div>
          <div class="option-check">
            <nut-checkbox v-model="paymentMethod" value="wechat" />
          </div>
        </div>
        <div 
          class="payment-option" 
          :class="{ active: paymentMethod === 'alipay' }"
          @click="paymentMethod = 'alipay'"
        >
          <div class="option-info">
            <img src="https://picsum.photos/24/24?random=1" alt="支付宝" class="payment-icon" />
            <span class="option-name">支付宝</span>
          </div>
          <div class="option-check">
            <nut-checkbox v-model="paymentMethod" value="alipay" />
          </div>
        </div>
      </div>
    </div>

    <!-- 订单备注 -->
    <div class="remark-section">
      <div class="section-title">订单备注</div>
      <nut-input 
        v-model="orderRemark" 
        placeholder="选填，请先和商家协商一致"
        type="textarea"
        :rows="3"
        class="remark-input"
      />
    </div>

    <!-- 费用明细 -->
    <div class="cost-section">
      <div class="section-title">费用明细</div>
      <div class="cost-list">
        <div class="cost-item">
          <span class="cost-label">商品总价</span>
          <span class="cost-value">¥{{ cartStore.selectedTotalPrice.toFixed(2) }}</span>
        </div>
        <div class="cost-item">
          <span class="cost-label">运费</span>
          <span class="cost-value">{{ deliveryMethod === 'express' ? `¥${deliveryFee}` : '免费' }}</span>
        </div>
        <div class="cost-item" v-if="selectedCoupon">
          <span class="cost-label">优惠券</span>
          <span class="cost-value">-¥{{ selectedCoupon.discount }}</span>
        </div>
        <div class="cost-item total">
          <span class="cost-label">实付金额</span>
          <span class="cost-value">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="checkout-bar">
      <div class="total-info">
        <div class="total-price">
          合计: <span class="price">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <div class="total-desc">
          含运费{{ deliveryMethod === 'express' ? `¥${deliveryFee}` : '免费' }}
        </div>
      </div>
      
      <div class="checkout-actions">
        <nut-button 
          type="primary" 
          size="large"
          :disabled="!canCheckout"
          @click="submitOrder"
          class="submit-btn"
        >
          提交订单
        </nut-button>
      </div>
    </div>

    <!-- 地址选择弹窗 -->
    <nut-popup v-model:visible="showAddressSelector" position="bottom" :style="{ height: '70%' }">
      <div class="address-popup">
        <div class="popup-header">
          <h3>选择收货地址</h3>
          <span class="close-btn" @click="showAddressSelector = false">×</span>
        </div>
                 <div class="address-list">
           <div 
             class="address-option" 
             v-for="address in addressStore.addressList" 
             :key="address.id"
             :class="{ active: selectedAddress?.id === address.id }"
             @click="selectAddressFromList(address)"
           >
             <div class="address-info">
               <div class="contact-info">
                 <span class="name">{{ address.name }}</span>
                 <span class="phone">{{ address.phone }}</span>
                 <span class="tag" v-if="address.tag">{{ address.tag }}</span>
                 <span class="default-badge" v-if="address.isDefault">默认</span>
               </div>
               <div class="address-detail">
                 {{ address.province }} {{ address.city }} {{ address.district }} {{ address.address }}
               </div>
             </div>
             <div class="address-actions">
               <div class="action-buttons">
                 <span class="edit-btn" @click.stop="editAddress(address.id)">编辑</span>
                 <span class="delete-btn" @click.stop="deleteAddress(address.id)" v-if="addressStore.addressList.length > 1">删除</span>
               </div>
               <div class="address-check">
                 <nut-checkbox :model-value="selectedAddress?.id === address.id" />
               </div>
             </div>
           </div>
         </div>
        <div class="popup-actions">
          <nut-button type="primary" @click="addNewAddress">新增地址</nut-button>
        </div>
      </div>
    </nut-popup>

    <!-- 优惠券选择弹窗 -->
    <nut-popup v-model:visible="showCouponSelector" position="bottom" :style="{ height: '70%' }">
      <div class="coupon-popup">
        <div class="popup-header">
          <h3>选择优惠券</h3>
          <span class="close-btn" @click="showCouponSelector = false">×</span>
        </div>
        <div class="coupon-list">
          <div 
            class="coupon-option" 
            v-for="coupon in availableCoupons" 
            :key="coupon.id"
            :class="{ active: selectedCoupon?.id === coupon.id }"
            @click="selectCouponFromList(coupon)"
          >
            <div class="coupon-info">
              <div class="coupon-amount">¥{{ coupon.discount }}</div>
              <div class="coupon-details">
                <div class="coupon-name">{{ coupon.name }}</div>
                <div class="coupon-condition">满{{ coupon.condition }}可用</div>
                <div class="coupon-expire">有效期至{{ coupon.expireDate }}</div>
              </div>
            </div>
            <div class="coupon-check">
              <nut-checkbox :model-value="selectedCoupon?.id === coupon.id" />
            </div>
          </div>
        </div>
        <div class="popup-actions">
          <nut-button type="default" @click="clearCoupon">不使用优惠券</nut-button>
        </div>
      </div>
    </nut-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { useAddressStore } from '@/stores/address'
import { Left, Right } from '@nutui/icons-vue'

const router = useRouter()
const cartStore = useCartStore()
const addressStore = useAddressStore()

// 状态管理
const showAddressSelector = ref(false)
const showCouponSelector = ref(false)
const deliveryMethod = ref('express')
const paymentMethod = ref('wechat')
const orderRemark = ref('')

// 收货地址
const selectedAddress = computed(() => addressStore.defaultAddress)

// 优惠券
const selectedCoupon = ref(null)
const availableCoupons = ref([
  {
    id: 1,
    name: '新人专享券',
    description: '满100减20',
    discount: 20,
    condition: 100,
    expireDate: '2024-12-31'
  },
  {
    id: 2,
    name: '满减优惠券',
    description: '满500减100',
    discount: 100,
    condition: 500,
    expireDate: '2024-12-31'
  }
])

// 运费
const deliveryFee = ref(10)

// 计算属性
const totalAmount = computed(() => {
  let total = cartStore.selectedTotalPrice
  if (deliveryMethod.value === 'express') {
    total += deliveryFee.value
  }
  if (selectedCoupon.value) {
    total -= selectedCoupon.value.discount
  }
  return Math.max(0, total)
})

const canCheckout = computed(() => {
  return selectedAddress.value && cartStore.selectedItems.length > 0
})

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 选择地址
const selectAddress = () => {
  showAddressSelector.value = true
}

// 从列表选择地址
const selectAddressFromList = (address) => {
  addressStore.setDefaultAddress(address.id)
  showAddressSelector.value = false
}

// 新增地址
const addNewAddress = () => {
  showAddressSelector.value = false
  router.push('/address-edit/new')
}

// 编辑地址
const editAddress = (addressId) => {
  showAddressSelector.value = false
  router.push(`/address-edit/${addressId}`)
}

// 删除地址
const deleteAddress = (addressId) => {
  if (addressStore.addressList.length <= 1) {
    showToast('至少需要保留一个地址')
    return
  }
  
  if (confirm('确定要删除这个地址吗？')) {
    const success = addressStore.deleteAddress(addressId)
    if (success) {
      showToast('地址删除成功')
    } else {
      showToast('地址删除失败')
    }
  }
}

// 选择优惠券
const selectCoupon = () => {
  showCouponSelector.value = true
}

// 从列表选择优惠券
const selectCouponFromList = (coupon) => {
  selectedCoupon.value = coupon
  showCouponSelector.value = false
}

// 清除优惠券
const clearCoupon = () => {
  selectedCoupon.value = null
  showCouponSelector.value = false
}

// 提交订单
const submitOrder = async () => {
  if (!canCheckout.value) {
    showToast('请完善订单信息')
    return
  }

  try {
    // 构建订单数据
    const orderData = {
      orderNo: 'ENBA' + Date.now(),
      createTime: new Date().toLocaleString(),
      productTotal: cartStore.selectedTotalPrice,
      deliveryFee: deliveryMethod.value === 'express' ? deliveryFee.value : 0,
      couponDiscount: selectedCoupon.value ? selectedCoupon.value.discount : 0,
      totalAmount: totalAmount.value,
      products: cartStore.selectedItems,
      address: selectedAddress.value,
      deliveryMethod: deliveryMethod.value,
      paymentMethod: paymentMethod.value,
      orderRemark: orderRemark.value
    }

    // 跳转到支付页面，传递订单数据
    router.push({
      path: '/payment',
      params: {
        orderData: encodeURIComponent(JSON.stringify(orderData))
      }
    })
    
  } catch (error) {
    showToast('订单提交失败，请重试')
    console.error('提交订单失败:', error)
  }
}

// 显示提示
const showToast = (message) => {
  console.log(message)
}

onMounted(() => {
  // 加载地址数据
  addressStore.loadFromLocalStorage()
})
</script>

<style scoped>
.header {
  background: white;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.placeholder {
  width: 24px;
}

.address-section,
.products-section,
.delivery-section,
.coupon-section,
.payment-section,
.remark-section,
.cost-section {
  background: white;
  margin-bottom: 12px;
  padding: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.address-item,
.coupon-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover,
.coupon-item:hover {
  border-color: #ff4757;
}

.address-info {
  flex: 1;
}

.contact-info {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
}

.name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.phone {
  font-size: 14px;
  color: #666;
}

.address-detail {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.no-address {
  color: #999;
  font-size: 14px;
}

.arrow {
  color: #ccc;
  font-size: 16px;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.product-item {
  display: flex;
  gap: 12px;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.product-image {
  width: 80px;
  height: 80px;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-spec {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 16px;
  color: #ff4757;
  font-weight: 600;
}

.quantity {
  font-size: 12px;
  color: #999;
}

.delivery-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.delivery-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.delivery-option:hover {
  border-color: #ff4757;
}

.delivery-option.active {
  border-color: #ff4757;
  background: rgba(255, 71, 87, 0.05);
}

.option-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.option-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.option-desc {
  font-size: 12px;
  color: #666;
}

.option-price {
  font-size: 14px;
  color: #ff4757;
  font-weight: 500;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.payment-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-option:hover {
  border-color: #ff4757;
}

.payment-option.active {
  border-color: #ff4757;
  background: rgba(255, 71, 87, 0.05);
}

.option-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.payment-icon {
  width: 24px;
  height: 24px;
  border-radius: 4px;
}

.option-name {
  font-size: 14px;
  color: #333;
}

.remark-input {
  width: 100%;
}

.cost-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.cost-item.total {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
  margin-top: 8px;
}

.cost-label {
  font-size: 14px;
  color: #333;
}

.cost-value {
  font-size: 14px;
  color: #333;
}

.cost-item.total .cost-label,
.cost-item.total .cost-value {
  font-size: 16px;
  font-weight: 600;
  color: #ff4757;
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.total-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.total-price {
  font-size: 14px;
  color: #333;
}

.price {
  font-size: 18px;
  font-weight: 600;
  color: #ff4757;
}

.total-desc {
  font-size: 12px;
  color: #666;
}

.submit-btn {
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  padding: 0 32px;
}

.address-popup,
.coupon-popup {
  padding: 20px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.popup-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.close-btn {
  font-size: 24px;
  color: #999;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.address-list,
.coupon-list {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.address-option,
.coupon-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-option:hover,
.coupon-option:hover {
  border-color: #ff4757;
}

.address-option.active,
.coupon-option.active {
  border-color: #ff4757;
  background: rgba(255, 71, 87, 0.05);
}

.coupon-amount {
  font-size: 20px;
  font-weight: 600;
  color: #ff4757;
  margin-bottom: 8px;
}

.coupon-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.coupon-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.coupon-condition,
.coupon-expire {
  font-size: 12px;
  color: #666;
}

.popup-actions {
  display: flex;
  gap: 12px;
}

/* 地址选项的新样式 */
.address-option {
  align-items: flex-start;
}

.address-info {
  flex: 1;
}

.contact-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.tag {
  background: #e3f2fd;
  color: #1976d2;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.default-badge {
  background: #ff4757;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.address-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.edit-btn,
.delete-btn {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-btn {
  color: #007bff;
  background: rgba(0, 123, 255, 0.1);
}

.edit-btn:hover {
  background: rgba(0, 123, 255, 0.2);
}

.delete-btn {
  color: #ff4757;
  background: rgba(255, 71, 87, 0.1);
}

.delete-btn:hover {
  background: rgba(255, 71, 87, 0.2);
}
</style>
